﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace YFurion.Security
{
    public class Des3
    {
        /// <summary>
        /// 字符串的加密
        /// </summary>
        /// <param name="value">要加密的字符串</param>
        /// <param name="key">密钥，必须32位</param>
        /// <returns>加密后的字符串</returns>
        public static string Encrypt(string value, string key)
        {
            try
            {
                byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 24));
                byte[] keyIV = new byte[8];
                Array.Copy(keyBytes, keyIV, keyIV.Length);
                byte[] inputByteArray = Encoding.UTF8.GetBytes(value);
                TripleDES tripleDES = TripleDES.Create();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, tripleDES.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                string str = Convert.ToBase64String(mStream.ToArray());
                return str;
            }
            catch (Exception ex)
            {
                return ("Error in Encrypting " + ex.Message);
            }
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="value">加密后的字符串</param>
        /// <param name="key">密钥，必须32位</param>
        /// <returns>解密后的字符串</returns>
        public static string Decrypt(string value, string key)
        {
            try
            {
                byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 24));
                byte[] keyIV = new byte[8];
                Array.Copy(keyBytes, keyIV, keyIV.Length);
                byte[] inputByteArray = Convert.FromBase64String(value);
                TripleDES tripleDES = TripleDES.Create();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, tripleDES.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray()).Replace("\\\\", "\\");
            }
            catch (Exception ex)
            {
                return ("Error in Decrypting " + ex.Message);
            }
        }
    }
}